//
//  GMInputView.m
//  Gmall
//
//  Created by yemeihua on 15/7/14.
//  Copyright (c) 2015年 Gmall. All rights reserved.
//

#import "GMInputView.h"
#import "FBKVOController.h"
#import <objc/message.h>

@interface GMInputView()<UITextViewDelegate>

@property (nonatomic,strong) FBKVOController *kvoController;

@end

@implementation GMInputView

@synthesize textView = _textView;
@synthesize inputTypeButton = _inputTypeButton;
@synthesize pluginButton = _pluginButton;
@synthesize emojiButton = _emojiButton;
@synthesize recodeButton = _recodeButton;

#pragma mark - 属性获取方法

- (UIButton *)inputTypeButton
{
    if(!_inputTypeButton)
    {
        _inputTypeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 49)];
        _inputTypeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
        [_inputTypeButton addTarget:self action:@selector(didTouchUpInsideInputTypeButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inputTypeButton;
}

- (UIButton *)pluginButton
{
    if(!_pluginButton)
    {
        _pluginButton = [[UIButton alloc] initWithFrame:CGRectMake(self.yc_width - 40, 0, 40, 49)];
        _pluginButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
        [_pluginButton setImage:[UIImage imageNamed:@"login_logo"] forState:UIControlStateNormal];
        [_pluginButton setImage:[UIImage imageNamed:@"login_logo"] forState:UIControlStateHighlighted];
        [_pluginButton addTarget:self action:@selector(didTouchUpInsideInputPluginButton:) forControlEvents:UIControlEventTouchUpInside];
        [_pluginButton setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];
    }
    return _pluginButton;
}

- (UIButton *)emojiButton
{
    if(!_emojiButton)
    {
        _emojiButton = [[UIButton alloc] initWithFrame:CGRectMake(self.yc_width - 40*2, 0, 40, 49)];
        _emojiButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
        [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
        [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateHighlighted];
        [_emojiButton addTarget:self action:@selector(didTouchUpInsideInputEmojiButton:) forControlEvents:UIControlEventTouchUpInside];
        [_emojiButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -5)];
    }
    return _emojiButton;
}

- (UITextView *)textView
{
    if(!_textView)
    {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(46, 7, self.yc_width - 46 - 40*2, 49 - 14)];
        _textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        _textView.font = [UIFont systemFontOfSize:15];
        _textView.backgroundColor = [UIColor yc_colorWithUInt:0xfcfcfd];
        _textView.layer.cornerRadius = 4;
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = [UIColor yc_colorWithUInt:0xc4c4c4].CGColor;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.layoutManager.allowsNonContiguousLayout = NO;
        _textView.delegate = self;
        _textView.enablesReturnKeyAutomatically = YES;
    }
    return _textView;
}

- (UIButton *)recodeButton
{
    if(!_recodeButton)
    {
        _recodeButton = [[UIButton alloc] initWithFrame:CGRectMake(46, 7, self.yc_width - 46 - 40*2, 49 - 14)];
        _recodeButton.layer.cornerRadius = 4;
        _recodeButton.layer.borderWidth = 0.5;
        _recodeButton.layer.borderColor = [UIColor yc_colorWithUInt:0xc1c0c5].CGColor;
        _recodeButton.layer.masksToBounds = YES;
        _recodeButton.adjustsImageWhenHighlighted = NO;
        _recodeButton.backgroundColor = [UIColor whiteColor];
        [_recodeButton setTitle:@"按住 说话" forState:UIControlStateNormal];
        _recodeButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [_recodeButton setBackgroundImage:[[UIImage yc_imageWithColor:[UIColor whiteColor] size:CGSizeMake(40, 40)] resizableImageWithCapInsets:UIEdgeInsetsZero] forState:UIControlStateNormal];
        [_recodeButton setTitleColor:[UIColor yc_colorWithUInt:0x565656] forState:UIControlStateNormal];
        [_recodeButton addTarget:self action:@selector(didTouchButton:withEvent:) forControlEvents:UIControlEventAllTouchEvents];
    }
    return _recodeButton;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    [self.textView becomeFirstResponder];
    return NO;
}

- (BOOL)resignFirstResponder
{
    [self.textView resignFirstResponder];
    return NO;
}

- (BOOL)isFirstResponder
{
    return self.textView.isFirstResponder;
}

#pragma mark - 视图生命周期

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        _shouldDismiss = YES;
        self.backgroundColor = [UIColor yc_colorWithUInt:0xf6f6f7];
        
        [self layout];
        
        self.kvoController = [FBKVOController controllerWithObserver:self];
        
        YCWeakSelf;
        
        [self.kvoController observe:self keyPath:@"inputType" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
            GMInputViewInputType type = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
            if(type == GMInputViewInputTypeKeyBoard)
            {
                _shouldDismiss = YES;
                CGSize size   = UIEdgeInsetsInsetRect(weakSelf.textView.bounds, weakSelf.textView.contentInset).size;
                size.height   = CGFLOAT_MAX;
                size          = [weakSelf.textView sizeThatFits:size];
                size.height += 14.0f;
                
                if(size.height > kScreenHeight * 0.25)
                {
                    size.height = kScreenHeight * 0.25;
                }
                
                CGRect frame = weakSelf.frame;
                frame.size.height = size.height;
                [weakSelf updateFrame:frame];
                
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice"] forState:UIControlStateNormal];
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice_"] forState:UIControlStateHighlighted];
                
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateHighlighted];
                
                weakSelf.textView.hidden = NO;
                weakSelf.recodeButton.hidden = YES;
            }
            else if(type == GMInputViewInputTypePlugin)
            {
                _shouldDismiss = NO;
                
                CGSize size   = UIEdgeInsetsInsetRect(weakSelf.textView.bounds, weakSelf.textView.contentInset).size;
                size.height   = CGFLOAT_MAX;
                size          = [weakSelf.textView sizeThatFits:size];
                size.height += 14.0f;
                
                if(size.height > kScreenHeight * 0.25)
                {
                    size.height = kScreenHeight * 0.25;
                }
                
                CGRect frame = weakSelf.frame;
                frame.origin.y = kScreenHeight - size.height - 64.0 - 260.0;
                frame.size.height = size.height;
                [weakSelf updateFrame:frame];

                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice"] forState:UIControlStateNormal];
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice_"] forState:UIControlStateHighlighted];
                
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateHighlighted];
                
                weakSelf.textView.hidden = NO;
                weakSelf.recodeButton.hidden = YES;
            }
            else if(type == GMInputViewInputTypeEmoji)
            {
                _shouldDismiss = NO;
                
                CGSize size   = UIEdgeInsetsInsetRect(weakSelf.textView.bounds, weakSelf.textView.contentInset).size;
                size.height   = CGFLOAT_MAX;
                size          = [weakSelf.textView sizeThatFits:size];
                size.height += 14.0f;
                
                if(size.height > kScreenHeight * 0.25)
                {
                    size.height = kScreenHeight * 0.25;
                }
                
                CGRect frame = weakSelf.frame;
                frame.origin.y = kScreenHeight - size.height - 64.0 - 260.0;
                frame.size.height = size.height;
                [weakSelf updateFrame:frame];

                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice"] forState:UIControlStateNormal];
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_voice_"] forState:UIControlStateHighlighted];
                
                [_emojiButton setImage:[UIImage imageNamed:@"input_keyboard"] forState:UIControlStateNormal];
                [_emojiButton setImage:[UIImage imageNamed:@"input_keyboard_"] forState:UIControlStateHighlighted];
                
                weakSelf.textView.hidden = NO;
                weakSelf.recodeButton.hidden = YES;
            }
            else
            {
                _shouldDismiss = YES;
                CGRect frame = weakSelf.frame;
                frame.size.height = 49;
                
                if(!weakSelf.textView.isFirstResponder)
                {
                    frame.origin.y = weakSelf.superview.yc_height - 49.0f;
                }
                [weakSelf updateFrame:frame];

                
                [weakSelf.textView resignFirstResponder];
                
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_keyboard"] forState:UIControlStateNormal];
                [_inputTypeButton setImage:[UIImage imageNamed:@"input_keyboard_"] forState:UIControlStateHighlighted];
                
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
                [_emojiButton setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateHighlighted];
                
                weakSelf.textView.hidden = YES;
                weakSelf.recodeButton.hidden = NO;
            }
        }];
        
        [self addTextViewContentSizeObserver];

        
        self.inputType = GMInputViewInputTypeKeyBoard;
    }
    return self;
}

- (void)dealloc
{
    [self removeKeyboardObserver];
}

- (void)updateFrame:(CGRect)frame
{
    self.frame = frame;
    if([self.delegate respondsToSelector:@selector(didInputView:changeFrame:)])
    {
        [self.delegate didInputView:self changeFrame:self.frame];
    }
}

- (void)updateTransform:(CGAffineTransform)transform
{
    self.transform = transform;
    if([self.delegate respondsToSelector:@selector(didInputView:changeFrame:)])
    {
        [self.delegate didInputView:self changeFrame:self.frame];
    }
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
}

#pragma mark - 自定义方法

- (void)layout
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, CGFloatFromPixel(1))];
    view.backgroundColor = [UIColor yc_colorWithUInt:0xc4c4c4];
    view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
    [self addSubview:view];
    
    [self addSubview:self.inputTypeButton];
    [self addSubview:self.textView];
    [self addSubview:self.pluginButton];
    [self addSubview:self.emojiButton];
    [self addSubview:self.recodeButton];
    
    view = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 0.5, kScreenWidth,CGFloatFromPixel(1))];
    view.backgroundColor = [UIColor yc_colorWithUInt:0xc4c4c4];
    view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self addSubview:view];
    
    self.recodeButton.hidden = YES;
}

- (void)didTouchUpInsideInputTypeButton:(UIButton *)inputTypeButton
{
    if(self.inputType != GMInputViewInputTypeVoice)
    {
        self.inputType = GMInputViewInputTypeVoice;
    }
    else
    {
        self.inputType = GMInputViewInputTypeKeyBoard;
        [self.textView becomeFirstResponder];
    }
}

- (void)didTouchUpInsideInputPluginButton:(UIButton *)pluginButton
{
    if([self.delegate respondsToSelector:@selector(didInputView:touchUpInsidePluginButton:)])
    {
        [self.delegate didInputView:self touchUpInsidePluginButton:pluginButton];
    }
}

- (void)didTouchUpInsideInputEmojiButton:(UIButton *)emojiButton
{
    if([self.delegate respondsToSelector:@selector(didInputView:touchUpInsideEmojiButton:)])
    {
        [self.delegate didInputView:self touchUpInsideEmojiButton:emojiButton];
    }
}

- (void)didTouchUpInsideRecodeButton:(UIButton *)recodeButton
{
    
}

- (void)didTouchButton:(UIButton *)button withEvent:(UIEvent *)event
{
    UITouch *touch = [event.allTouches anyObject];
    SEL selector = NULL;
    
    switch (touch.phase)
    {
        case UITouchPhaseBegan:
            [_recodeButton setTitle:@"松开 结束" forState:UIControlStateNormal];
            [_recodeButton setBackgroundImage:[[UIImage yc_imageWithColor:[UIColor yc_colorWithUInt:0xc6c7c8] size:CGSizeMake(40, 40)] resizableImageWithCapInsets:UIEdgeInsetsZero] forState:UIControlStateNormal];
            selector = @selector(didInputView:recodeButton:beginTouch:);
            break;
            
        case UITouchPhaseMoved:
            selector = @selector(didInputView:recodeButton:moveTouch:);
            break;
            
        default:
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [_recodeButton setTitle:@"按住 说话" forState:UIControlStateNormal];
                [_recodeButton setBackgroundImage:[[UIImage yc_imageWithColor:[UIColor whiteColor] size:CGSizeMake(40, 40)] resizableImageWithCapInsets:UIEdgeInsetsZero] forState:UIControlStateNormal];
            });

            selector = @selector(didInputView:recodeButton:endTouch:);
            break;
    }
    void (* GM_objc_msgSend)(id,SEL,id,id,id) = (void (*)(id,SEL,id,id,id))objc_msgSend;

    if([self.delegate respondsToSelector:selector])
    {
        GM_objc_msgSend(self.delegate,selector,self,button,touch);
    }
}

#pragma mark - 观察相关

- (void)addKeyboardObserver
{
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)didReceiveKeyboardWillShowNotification:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat height = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    [UIView animateWithDuration:duration
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         CGRect rect = self.frame;
                         rect.origin.y = self.superview.yc_height - height - rect.size.height;
                         [self updateFrame:rect];
                     }
                     completion:nil];
}

- (void)didReceiveKeyboardWillHideNotification:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         if(self.shouldDismiss)
                         {
                             CGRect rect = self.frame;
                             rect.origin.y = self.superview.yc_height - rect.size.height;
                             [self updateFrame:rect];
                         }
                     }
                     completion:nil];
}

- (void)removeKeyboardObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)addTextViewContentSizeObserver
{
    YCWeakSelf;
    [self.kvoController observe:self.textView
                        keyPath:@"contentSize"
                        options:NSKeyValueObservingOptionNew
                          block:^(id observer, id object, NSDictionary *change) {
                              
                              //NSLog(@"size:%@",NSStringFromCGSize([[change objectForKey:NSKeyValueChangeOldKey] CGSizeValue]));
                              //NSLog(@"size:%@",NSStringFromCGSize([[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue]));
                              
                              CGFloat new = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue].height;
                              new += 14;
                              
                              if(new < kScreenHeight * 0.25)
                              {
                                  new = new < 49 ? 49 : new;
                                  
                                  CGRect frame = weakSelf.frame;
                                  CGFloat o = new - frame.size.height;
                                  frame.size.height = new;
                                  [weakSelf updateFrame:frame];

                                  
                                  CGAffineTransform transform = CGAffineTransformTranslate(weakSelf.transform, 0, -o);
                                  weakSelf.transform = CGAffineTransformIdentity;
                                  [weakSelf updateTransform:transform];
                                  
                                  if([weakSelf.delegate respondsToSelector:@selector(didInputView:changeFrame:)])
                                  {
                                      [weakSelf.delegate didInputView:weakSelf changeFrame:weakSelf.frame];
                                  }
                                  
                                  [UIView animateWithDuration:0.01
                                                        delay:0.01
                                                      options:UIViewAnimationOptionCurveLinear
                                                   animations:^{
                                                       
                                                       [self.textView scrollRangeToVisible:weakSelf.textView.selectedRange];
                                                   }
                                                   completion:nil];
                              }
                              else
                              {
                                  [weakSelf.textView scrollRangeToVisible:NSMakeRange(weakSelf.textView.text.length,1)];
                              }
                          }];
}

- (void)removeTextViewContentSizeObserver
{
    [self.kvoController unobserve:self.textView keyPath:@"contentSize"];
}

#pragma mark - UITextView delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [self removeKeyboardObserver];
    [self addKeyboardObserver];
    
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        if([self.delegate respondsToSelector:@selector(didInputView:sendText:)])
        {
            [self.delegate didInputView:self sendText:textView.text];
        }
        textView.text = @"";
        return NO;
    }
    return YES;
}

- (void)reset
{
    self.shouldDismiss = YES;
    if(self.textView.isFirstResponder)
    {
        [self.textView resignFirstResponder];
    }
    else
    {
        CGRect frame = self.frame;
        frame.size.height = 49;
        frame.origin.y = self.superview.yc_height - 49.0f;
        [self updateFrame:frame];

    }
}

@end
